package com.heima.schedule.service.Impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class TaskServiceImpl implements TaskService {
    @Resource
    private TaskinfoMapper taskinfoMapper;
    @Resource
    private TaskinfoLogsMapper taskinfoLogsMapper;
    @Resource
    private CacheService cacheService;
    /**
     * 添加任务
     *
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    public long addTask(Task task) {
        //参数校验
        if(null==task||null==task.getParameters()){
            return -1;
        }
        //把任务添加到数据库--》状态
        boolean flag=addTaskDB(task);
        //如果添加数据库成功 再把数据添加到redis
        if (flag){
            addTaskRedis(task);
        }
        return task.getTaskId();
    }

    /**
     * 取消任务
     *
     * @param taskId 任务id
     * @return 取消结果
     */
    @Override
    public boolean cancelTask(long taskId) {
        boolean flag=true;
        //删除任务，更新日志
        Task task=updateDb(taskId,ScheduleConstants.CANCELLED);
        //删除redis的数据
        if (task!=null){
            removeTaskFromCache(task);
            flag=true;
        }
        return flag;
    }

    /**
     * 按照类型和优先级来拉取任务
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        String key = type + ":" + priority;
        String json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
        if (!StringUtils.isEmpty(json)) {
            Task task = JSON.parseObject(json, Task.class);
            //更新数据库的状态
            updateDb(task.getTaskId(),ScheduleConstants.EXECUTED);
            return task;

        }
        return null;
    }

    private void removeTaskFromCache(Task task) {
        String key = task.getTaskType() + ":" + task.getPriority();
        if (task.getExecuteTime()<=System.currentTimeMillis()){
            cacheService.lRemove(ScheduleConstants.TOPIC+key,0,JSON.toJSONString(task));
        }else {
            cacheService.zRemove(ScheduleConstants.FUTURE+key,JSON.toJSONString(task));
        }
    }

    private Task updateDb(long taskId, int status) {
        Task task=null;
        try {
            //删除任务
            taskinfoMapper.deleteById(taskId);
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);
            task=new Task();
            BeanUtils.copyProperties(taskinfoLogs,task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        }catch (Exception e){
            e.printStackTrace();
            log.error("task cancel exception taskid={}",taskId);
        }
        return task;
    }

    private void addTaskRedis(Task task) {
        //构建redis的key
        String key = task.getTaskType() + ":" + task.getPriority();
        //获取未来5分钟的时间
        Calendar instance=Calendar.getInstance();
        instance.add(Calendar.MINUTE,5);
        //判断是否是立即执行 还是未来5分钟执行的
        if(task.getExecuteTime()<=System.currentTimeMillis()){
            //立即执行
            cacheService.lLeftPush(ScheduleConstants.TOPIC+key, JSON.toJSONString(task));
        }else if (task.getExecuteTime()<=instance.getTimeInMillis()){
            //未来5分钟要执行的任务
            cacheService.zAdd(ScheduleConstants.FUTURE+key,JSON.toJSONString(task),task.getExecuteTime());
        }
    }

    private boolean addTaskDB(Task task) {
        boolean flag=true;
        try {
            //添加任务
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);
            //把id重新写入task
            task.setTaskId(taskinfo.getTaskId());
            //添加任务的日志
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(task,taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogs.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoLogsMapper.insert(taskinfoLogs);
        } catch (Exception e) {
            e.printStackTrace();
            flag=false;
        }
        return flag;
    }
//    @Scheduled(cron = "0 */1 * * * ?")
    @Scheduled(cron = "*/5 * * * * ?")
    public void refresh(){
        log.info("定时任务开始");
        Set<String> set = cacheService.scan(ScheduleConstants.FUTURE + "*");
        if (null!=set&&set.size()>0){
            //如果不为空，则遍历每一个set集合
            set.forEach(key->{
                //从set中找到过期的数据
                Set<String> values = cacheService.zRangeByScore(key, 0, System.currentTimeMillis());
                if (null!=values&&values.size()>0){
                    //把过期数据拷贝到list集合
                    String targetKey = key.replace(ScheduleConstants.FUTURE, ScheduleConstants.TOPIC);
                    cacheService.refreshWithPipeline(key,targetKey,values);
                }
            });
        }
        log.info("定时任务结束了");
    }
    @PostConstruct
    @Scheduled(cron = "*/5 * * * * ?")
    public void reloadData(){
        //清除redis的list和zset的数据
        clearCache();
        //获取未来5分钟的时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE,5);
        //根据这个时间查询未来的任务
        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().le(Taskinfo::getExecuteTime, instance.getTime()));
        //遍历每一个任务 然后判断执行的时间是否到了 如果到了就加到List 如果没有到则加到zset
        if (null!=taskinfoList&&taskinfoList.size()>0){
            Task task=new Task();
            for (Taskinfo taskinfo : taskinfoList) {
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskRedis(task);
            }
        }
    }

    private void clearCache() {
        Set<String> futureSet = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topicSet = cacheService.scan(ScheduleConstants.TOPIC + "*");
        cacheService.delete(futureSet);
        cacheService.delete(topicSet);
    }
}
